package com.hieubq.demo.screenlock.theme.snail.activity;

import java.util.Calendar;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.hieubq.demo.screenlock.theme.snail.R;
import com.hieubq.demo.screenlock.theme.snail.locker.LockSlider;
import com.hieubq.demo.screenlock.theme.snail.locker.LockSliderAccessor;
import com.hieubq.demo.screenlock.theme.snail.receiver.ScheduleReceiver;
import com.hieubq.demo.screenlock.theme.snail.assets.Assets;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;
import aurelienribon.tweenengine.equations.Back;

public class LockScreenActivity extends Activity {

	private TweenManager tweenManager;
	private boolean isAnimationRunning = true;
	private ImageView m_slider;
	private LockSlider m_locSlider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_lock_screen);

		m_slider = (ImageView) findViewById(R.id.slider);
		setTweenEngine();

		m_slider.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int eventaction = event.getAction();

				switch (eventaction) {
				case MotionEvent.ACTION_DOWN:
					// finger touches the screen
					m_locSlider = new LockSlider();
					m_locSlider.view = m_slider;

					Tween.to(m_locSlider, LockSliderAccessor.SCALE_XY, 0.5f)
							.ease(Back.INOUT).target(2, 2).repeatYoyo(-1, 0.6f)
							.start(tweenManager);

					break;

				case MotionEvent.ACTION_MOVE:
					// finger moves on the screen
					Tween.set(m_locSlider, LockSliderAccessor.POSITION_X)
							.target(event.getRawX()).start(tweenManager);
					break;

				case MotionEvent.ACTION_UP:
					// finger leaves the screen
					v.setVisibility(View.GONE);
					finish();
					break;
				}

				// tell the system that we handled the event and no further
				// processing is required
				return true;
			}
		});
		
		
		
		AlarmManager service = (AlarmManager) this
				.getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(this, ScheduleReceiver.class);
		PendingIntent pending = PendingIntent.getBroadcast(this, 0, i,
				PendingIntent.FLAG_CANCEL_CURRENT);
		Calendar cal = Calendar.getInstance();
		// Start 30 seconds after boot completed
		cal.add(Calendar.SECOND, 1);
		//
		// Fetch every 30 seconds
		// InexactRepeating allows Android to optimize the energy consumption
		service.setInexactRepeating(
				AlarmManager.RTC_WAKEUP,
				cal.getTimeInMillis(),
				com.hieubq.demo.screenlock.theme.snail.receiver.StartupReceiver.REPEAT_TIME,
				pending);

		this.startService(new Intent(
				this,
				com.hieubq.demo.screenlock.theme.snail.service.MonitorService.class));
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			return false;
		} else
			return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		this.getWindow().setType(
				WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
						| WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onAttachedToWindow();
	}

	private void setTweenEngine() {
		tweenManager = new TweenManager();
		Assets.inst().load("assets/slider.png", Texture.class);
		Assets.inst().load("assets/bg.png", Texture.class);
		setAnimationThread();

		// **Register Accessor, this is very important to do!
		// You need register actually each Accessor, but right now we have
		// global one, which actually suitable for everything.
		Tween.registerAccessor(LockSlider.class, new LockSliderAccessor());
	}

	private void setAnimationThread() {

		new Thread(new Runnable() {
			private long lastMillis = -1;

			@Override
			public void run() {
				while (isAnimationRunning) {
					if (lastMillis > 0) {
						long currentMillis = System.currentTimeMillis();
						final float delta = (currentMillis - lastMillis) / 1000f;

						/*
						 * view.post(new Runnable(){
						 * 
						 * @Override public void run() {
						 * 
						 * } });
						 */
						/**
						 * We run all animation in UI thread instead of using
						 * post for each elements.
						 */
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								tweenManager.update(delta);

							}
						});

						lastMillis = currentMillis;
					} else {
						lastMillis = System.currentTimeMillis();
					}

					try {
						Thread.sleep(1000 / 60);
					} catch (InterruptedException ex) {
					}
				}
			}
		}).start();

	}

	private void setAnimationFalse() {
		isAnimationRunning = false;
	}

	/**
	 * Make animation thread alive
	 */
	private void setAnimationTrue() {
		isAnimationRunning = true;
	}

}
